<?php

namespace SmmsSdk\Auth;

use Hanson\Foundation\AbstractAccessToken;
use http\Exception;
use SmmsSdk\Application;

class AccessToken extends AbstractAccessToken
{


    /**
     * @var string
     */
    protected $token;


    /**
     * @var string
     */
    protected $cachePrefix = 'lzh1104.auth.access_token.';

    /**
     * Response Json key name of token.
     *
     * @var string
     */
    protected $tokenJsonKey = 'token';

    /**
     * Response Json key name of token.
     *
     * @var string
     */
    protected $expiresJsonKey = 'expire';

    public function getTokenFromServer()
    {
        $params = [
            'username' => $this->app->getConfig('auth')['username'],
            'password' => $this->app->getConfig('auth')['password']
        ];

        $info = $this->getHttp()->post($this->app->getConfig('base_url') . '/token', $params);
        $result = json_decode(strval($info->getBody()), true);
        if (!$result || !$result['success']) {
            return [];
        }
        if (empty($result['data']['token'])) {
            return $result;
        }
        return [$this->tokenJsonKey => $result['data']['token'], $this->expiresJsonKey => 30 * 86400];
    }

    public function checkTokenResponse($result)
    {
        if (empty($result)) {
            throw new \Hanson\Foundation\Exception\HttpException("token 返回为空");
        }
        if (empty($result[$this->tokenJsonKey])) {
            throw new \Hanson\Foundation\Exception\HttpException($result['message']);
        }
    }

    /**
     * @return string
     */
    public function getCacheKey()
    {
        return $this->cachePrefix.md5(json_encode($this->app->getConfig('auth')));
    }


}